package com.lx.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

/**过滤器主要打印日志
 * @author lixing
 * @date 2021/11/24 9:49
 */
@Slf4j
@Component
public class GlobalFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("System init ....");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long beginTime = System.currentTimeMillis();
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String url = req.getServletPath();
        filterChain.doFilter(servletRequest,servletResponse);
        StringBuffer stb = new StringBuffer();
        Enumeration<String> enu = servletRequest.getParameterNames();
        while(enu.hasMoreElements()) {
            String key = enu.nextElement();
            stb.append(key + "=" + servletRequest.getParameter(key) + "&");
        }
        log.info(String.format("%s URL: %s %sms params:%s",req.getMethod(),url,System.currentTimeMillis()-beginTime,stb.toString()));
    }

    @Override
    public void destroy() {
        log.info("System destroy ...");
    }
}
